package com.example.fw;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.GroupData;
import com.example.utils.SortedListOf;

public class GroupHelper extends WebDriverHelperBase {
	
	public GroupHelper(ApplicationManager manager) {
		super(manager);
	}

	public GroupHelper createGroup(GroupData i_group) {
		manager.navigateTo().groupsPage();
		initGroupCreation();
		fillGroupForm(i_group);
		submitGroupCreation();
		returnToGroupPage();
		manager.getModel().addGroup(i_group);
		return this;
	}

	public GroupHelper deleteGroup(int i_indx) {
		selectGroupByIndex(i_indx);
		submitGroupDelition();
		returnToGroupPage();
		manager.getModel().deleteGroup(i_indx);
		return this;
 	}

	public GroupHelper modifyGroup(int i_indx, GroupData i_group) {
		manager.navigateTo().groupsPage();
		initGroupModification(i_indx);
		fillGroupForm(i_group);
		submitGroupModification();
		returnToGroupPage();
		manager.getModel().deleteGroup(i_indx).addGroup(i_group);
		return this;
	}

	//-----------------------------------------------------------------------------------------------	
	
	public SortedListOf<GroupData> getUiGroups() {
		SortedListOf<GroupData> groups = new SortedListOf<GroupData>();

		manager.navigateTo().groupsPage();
		List<WebElement> checkboxes = driver.findElements(By.name("selected[]"));
		for (WebElement checkbox : checkboxes) {
			
			String title = checkbox.getAttribute("title");
			String name = title.substring("Select (".length(), title.length() - ")".length());
			groups.add(new GroupData().withName(name));
		}
		return groups;
	}

	private void selectGroupByIndex(int i_index) {
		click(By.xpath("//input[@name='selected[]']["+(i_index+1)+"]"));
	}

	public void returnToGroupPage() {
		click(By.linkText("group page"));
	}

	public GroupHelper initGroupCreation() {
		manager.navigateTo().groupsPage();
		click(By.name("new"));
		return this;
	}

	public GroupHelper fillGroupForm(GroupData group) {
		type(By.name("group_name"), group.getName());
		type(By.name("group_header"), group.getHeader());
		type(By.name("group_footer"), group.getFooter());
		return this;
	}

	public GroupHelper submitGroupCreation() {
		click(By.name("submit"));
		//cachedGroups = null;
		return this;
	}

	public GroupHelper openGroupPage() {
		driver.get(manager.baseUrl + "/addressbookv4.1.4/?group=");
		return this;
	}

	public GroupHelper initGroupModification(int i_index) {
		selectGroupByIndex(i_index);
		click(By.name("edit"));
		return this;
	}

	public GroupHelper submitGroupModification() {
		click(By.name("update"));
		return this;
	}
	/**
	 * 
	 */
	private void submitGroupDelition() {
		click(By.name("delete"));
	}
}
